package heap.medium;


import java.util.PriorityQueue;

/**
 * 数组中的第K个最大元素
 * 示例 1:
 *
 * 输入: [3,2,1,5,6,4] 和 k = 2
 * 输出: 5
 * 示例 2:
 *
 * 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
 * 输出: 4
 * 链接：https://leetcode-cn.com/problems/kth-largest-element-in-an-array
 */
public class KthLargestElementInAnArray_215 {

    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> heap = new PriorityQueue<>();
        for (int num : nums) {
            heap.offer(num);
            if (heap.size() > k)
                heap.poll();
        }
        return heap.peek();
    }
}
